package remote

import (
	"bytes"
	"fmt"
	"log"
	"net"

	D "gitee.com/dark.H/go-remote-repl/datas"
)

const (
	SEP = "<SEP>"
)

type ApiServerMan struct {
	con            net.Conn
	RidEFunc       func(con net.Conn)
	HandleRecvJson func(data D.Gi)
}

func ApiServerManWraper(conn net.Conn) (man *ApiServerMan) {
	man = new(ApiServerMan)
	man.con = conn
	if err := man.WhatToDo(); err != nil {
		log.Println("what to do err:", err)
		man.con.Close()
		man = nil
	}
	return
}
func AsApiServer(conn net.Conn) (man *ApiServerMan) {
	man = new(ApiServerMan)
	man.con = conn
	return
}

func NewApiServer(conn net.Conn) (man *ApiServerMan) {
	man = new(ApiServerMan)
	man.con = conn
	if err := man.WhatToDo(); err != nil {
		log.Println("what to do err:", err)
		man.con.Close()
		man = nil
	}
	return
}

func (m *ApiServerMan) SendMsg(msg string) {
	m.con.Write([]byte(msg))
}

func (m *ApiServerMan) ReadMsg() string {
	buf := make([]byte, 4096)
	n, err := m.con.Read(buf)
	if err != nil {
		log.Println("man read msg err:", err)
		m.con.Close()
		return ""
	}
	return string(buf[:n])
}

func (m *ApiServerMan) DbCli() {
	m.con.Write([]byte("config:"))
	buf := make([]byte, 1024)
	n, err := m.con.Read(buf)
	if err != nil {
		log.Println("getcmd err:", err)
		m.con.Close()
		return
	}
	if bytes.HasPrefix(buf[:n], []byte("::config::")) {
		D.WriteALl(m.con, []byte("ok"))
		fmt.Println("server: ok")
		D.MemDB.ConfigCliServer(m.con)
	}

	return
}
